//
//  LZRestaurantAuthenticationViewController.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/3/3.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZRestaurantAuthenticationViewController.h"
#import "LZRestaurantAuthTableSectionHeadView.h"
#import "LZRestaurantAuthTextCell.h"
#import "LZRestaurantAuthSelectCell.h"
#import "LZRestaurantAuthLicenseCell.h"
#import "LZRestaurantAuthOpenTimeSelectCell.h"
#import "UIViewController+NavigationItemSetting.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "LZRestaurantAuthModel.h"
#import "LZPopSelectView.h"
#import "LZPopSelectCollectViewModel.h"
#import "LZSelectDateView.h"
#import "LZActionSheet.h"
#import "LZImagePickerManager.h"
#import "LZRestaurantAuthPresenter.h"
#import "LZUploadImagePresenter.h"
#import "LZUserModel.h"
#import "LZRemindView.h"
#import "LZAlertView.h"
#import "LZPaymentAccountViewController.h"
#import "LZRestaurantAuthSuccessViewController.h"
#import "LZRestaurantAuthRejectedView.h"
#import "LZMapViewController.h"
#import "LZUserInfoPresenter.h"
#import "extobjc.h"
#import "MJExtension.h"
#import "CityManager.h"
#import "CitysModel.h"
#import "GVUserDefaults.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZSearchCityViewController.h"

static NSString *textCell = @"textcell";
static NSString *selectCell = @"selectcell";
static NSString *openTimeCell = @"opentimecell";
static NSString *licenseCell = @"licensecell";
static NSString *sectionHead = @"sectionHead";

@interface LZRestaurantAuthenticationViewController ()<UITableViewDelegate,UITableViewDataSource,LZRestaurantAuthTextCellDelegate,LZRestaurantAuthSelectCellDelegate,LZRestaurantAuthLicenseCellDelegate,LZRestaurantAuthOpenTimeCellDelegate,LZPictureManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView      *tableView;
@property (weak, nonatomic) IBOutlet UIImageView      *sectionHeadImgView;
@property (weak, nonatomic) IBOutlet UILabel          *sectionHeadTitleLabel;
@property (strong, nonatomic) __block NSArray         *selectedCuisineArr; //已经选择的菜系数组
@property (strong, nonatomic) __block NSArray         *selectedAreaArr;  //已经选择的商区数组
@property (strong, nonatomic) UIButton                *submitBtn;
@property (strong, nonatomic) UIImage                 *licenseImg;   //营业执照
@property (strong, nonatomic) LZPopSelectView         *selectView;
@property (strong, nonatomic) LZSelectDateView        *selectTimeView;
@property (weak, nonatomic) LZActionSheet           * actionSheet;
@property (strong, nonatomic) LZImagePickerManager    * pictureManager;
@property (strong, nonatomic) LZRestaurantAuthModel   *authModel;
@property (strong, nonatomic) LZRestaurantAuthPresenter *authPresenter;
@property (strong, nonatomic) LZUploadImagePresenter    * uploadImagePresenter;
@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (nonatomic, strong) NSString *cookeStyleIDStr;
@property (nonatomic, assign) BOOL isWaitAuth; //是否是等待认证审核
@end

@implementation LZRestaurantAuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureUI];
    
    [self configureData];
    
    [self configureNavBar];
    
    if (self.regected) {//如果是被驳回.填充值
        [self getRestaurantInfo];
    }
    
    //当等待认证，或者认证完成后，再次通过消息列表进入本页（这两种状态下，只有消息列表能够进入），不可编辑
    if ([GVUserDefaults standardUserDefaults].authType == kAuthType_waitAuth || [GVUserDefaults standardUserDefaults].authType == kAuthType_completeAuth) {
        self.submitBtn.hidden = YES;
        self.submitBtn.enabled = NO;
        self.isWaitAuth = YES;
    }
}

#pragma mark -
#pragma mark UI NavBar
- (void)configureUI
{
    self.umLogPageViewName = @"商户认证";
    self.title = LZLocalizedString(@"res_auth_restaurant_authentication", nil);
    self.authModel = [[LZRestaurantAuthModel alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LZRestaurantAuthTextCell" bundle:nil] forCellReuseIdentifier:textCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZRestaurantAuthSelectCell" bundle:nil] forCellReuseIdentifier:selectCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZRestaurantAuthLicenseCell" bundle:nil] forCellReuseIdentifier:licenseCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZRestaurantAuthOpenTimeSelectCell" bundle:nil] forCellReuseIdentifier:openTimeCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LZRestaurantAuthTableSectionHeadView" bundle:nil] forHeaderFooterViewReuseIdentifier:sectionHead];
}

- (void)configureNavBar
{
    self.submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.submitBtn.frame = CGRectMake(0, 0, 60, 40);
    self.submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.submitBtn.userInteractionEnabled = self.regected;
    if (self.regected) {
        [self.submitBtn setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
    }else{
        [self.submitBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    }
    
    [self.submitBtn setTitle:LZLocalizedString(@"submit_min", nil) forState:UIControlStateNormal];
    [self.submitBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    [self navigationItemSetting:@[self.submitBtn] type:NAVIGATIONITEMSETTING_RIGHT];
}

- (void)configureData
{
    _userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    [self getRestaurantAreaArrAction];
    [self getRestaurantCuisineArrAction];
}

#pragma mark -
#pragma mark network priva event

- (void)getRestaurantInfo
{
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
    @weakify(self);
    [self.userInfoPresenter userGetMerchantInfoSuccess:^(id data) {
        DLog(@"%@", data);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
        self.authModel = [LZRestaurantAuthModel mj_objectWithKeyValues:data[@"data"]];
        LZRestaurantAuthRejectedView *v = [[NSBundle mainBundle] loadNibNamed:@"LZRestaurantAuthRejectedView" owner:self options:nil].lastObject;
        [v loadReasonText:self.authModel.reviewComments titleText:LZLocalizedString(@"res_auth_reason_for_rejection", nil)];
        v.frame = CGRectMake(0, 0, SCREEN_WIDTH, [v intrinsicContentSize].height);
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, v.frame.size.height)];
        [bgView addSubview:v];
        self.tableView.tableHeaderView = bgView;

        [self fillCookingStyleAndHotAreaWhenAuthRegetced];
        
        //记录本地返回的值.在最后提交时判断.如果一样,则清空,后台就不会处理了.如果不一致,说明修改了菜系,则正常提交
        self.cookeStyleIDStr = self.authModel.cookingStyle;
        
        [self.tableView reloadData];
        
    } onFail:^(NSString *fail) {
        DLog(@"%@", fail);
        @strongify(self);
        [self stopLoadingViewForView:self.view];
    }];
}

/**
 获取菜系
 */
- (void)getRestaurantCuisineArrAction
{
  [self.authPresenter getRestaurantCuisineSuccess:^(NSArray *cuisineArr) {
      DLog(@"get restaurant cuisine success");
  } Failure:^(NSString *fail) {
      
  }];
}


/**
 获取热门商区
 */
- (void)getRestaurantAreaArrAction
{
  [self.authPresenter getHotAreaSuccess:^(NSArray *areaArr) {
      DLog(@"get restaurant area success");
  } Failure:^(NSString *fail) {
      
  }];
}

/**
 保存方法
 */
- (void)saveAction
{
    if (self.regected) {
        [self regetcedAndAuthAgainAction];
    }else{
        [self firstAuthAction];
    }

}


/**
 首次认证
 */
- (void)firstAuthAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_alert", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    @weakify(self);
    alert.clickButtonIndexBlock = ^(NSInteger index){
        @strongify(self);
        if (index == 1) {
            [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
            [self.authPresenter authRestaurantWithModel:self.authModel Success:^(id data) {
                @strongify(self);
                DLog(@"save success");
                [self stopLoadingViewForView:self.view];
                [GVUserDefaults standardUserDefaults].sellerId = data[@"data"];
                [GVUserDefaults standardUserDefaults].authType = kAuthType_waitAuth;
                LZRestaurantAuthSuccessViewController *vc = [[LZRestaurantAuthSuccessViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                
            } Failure:^(NSString *fail) {
                @strongify(self);
                [self saveFailureAction];
                [self stopLoadingViewForView:self.view];
            }];
        }
    };

}


/**
 认证被拒,修改后,再次认证
 */
- (void)regetcedAndAuthAgainAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_alert", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    @weakify(self);
    alert.clickButtonIndexBlock = ^(NSInteger index){
        @strongify(self);
        if (index == 1) {
            
            if ([self.authModel.cookingStyle isEqualToString:self.cookeStyleIDStr]) {
                self.authModel.cookingStyle = nil;
            }
            [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:NO];
            
            [self.authPresenter authRestaurantAgainWithModel:self.authModel Success:^(id data) {
                @strongify(self);
                [self stopLoadingViewForView:self.view];
                DLog(@"save success");
                [GVUserDefaults standardUserDefaults].authType = kAuthType_waitAuth;
                LZRestaurantAuthSuccessViewController *vc = [[LZRestaurantAuthSuccessViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                
            } Failure:^(NSString *fail) {
                @strongify(self);
                [self saveFailureAction];
                [self stopLoadingViewForView:self.view];
            }];
        }
    };
}

/**
 提交认证信息失败提醒
 */
- (void)saveFailureAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"submit_fail", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"confirm", nil) otherButtonTitles:nil];
    [alert show];
}

- (void)uploadImg:(UIImage *)img
{
    //上传头像
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    @weakify(self);
    [self.uploadImagePresenter uploadImage:img
                             andBusinessId:[LZUserModel Instance].sellerId
                           andBusinessType:@"8"
                             andBusinessNo:@"1"
                                andIsThumb:NO
                                   andSize:CGSizeZero
                              andonSuccess:^(id data) {
                                  @strongify(self);
                                  //上传成功获取路径
                                  NSArray *resultArray = data[@"data"];
                                  if (resultArray.count>0) {
                                      NSDictionary *dic = resultArray[0];
                                      NSString *filePath = dic[@"filePath"];
                                      self.authModel.licencePhoto = filePath;
                                      [self.tableView reloadData];
                                  }
                                  [self stopLoadingViewForView:self.view];
                                  [self changeSubmitStateAction];
                                  
                              } onFail:^(NSString *fail) {
                                  
                                  [self stopLoadingViewForView:self.view];
                                  [self uploadLicenseFailureAction];
                                  
                              }];
    
}


/**
 执照提交失败,从新提交
 */
- (void)uploadLicenseFailureAction
{
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"res_auth_license_upload_failure", nil) andImage:nil cancelButtonTitle:LZLocalizedString(@"cancel", nil) otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    @weakify(self);
    alert.clickButtonIndexBlock = ^(NSInteger index){
        @strongify(self);
        if (index == 1) {
            if (self.licenseImg) {
                [self uploadImg:self.licenseImg];
            }
        }
    };
}


#pragma mark - local private event
/**
 选择图片方式方法

 @param buttonIndex <#buttonIndex description#>
 */
- (void)LASheetClickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType = 0;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        if (buttonIndex == 0) {
            // TakePhotos
            sourceType = UIImagePickerControllerSourceTypeCamera;
        } else if (buttonIndex == 1) {
            // PhotoAlbums
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    } else {
        if (buttonIndex == 0) {
            return;
        } else {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    
    [self.pictureManager choosePictureWithSourceType:sourceType andPresenterVC:self];
}


/**
 获取图片方法

 @param info <#info description#>
 */
- (void)LZPictureManagerFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.licenseImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (self.licenseImg) {
        [self uploadImg:self.licenseImg];
    }
}


/**
 刷新相应的cell
 
 @param section <#section description#>
 @param row <#row description#>
 */
- (void)reloadTableViewSection:(NSInteger)section row:(NSInteger)row
{
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:row inSection:section]] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView endUpdates];
}


/**
 展示 菜系选则的view
 */
- (void)showCuisineSelectView
{
    self.selectView.canSelectMore = YES;
    [self.selectView loadTitle:LZLocalizedString(@"res_auth_cuisine", nil)];
    [self.selectView loadDataArr:[self.authPresenter getRestaurantCuisineArrForPopSelectViewBaseSelectedCuisineArr:self.selectedCuisineArr]];
    [self.selectView showSelfAnimation];
    @weakify(self);
    self.selectView.selectedItemsBlock = ^(NSArray *resultArr){
        @strongify(self);
        self.selectedCuisineArr = resultArr;
        NSString *cuisineIDStr = nil;
        NSString *cuisineNameStr = nil;
        for (int i=0; i < resultArr.count; i ++) {
            LZPopSelectCollectViewModel *m = resultArr[i];
            if (i == 0) {
                cuisineIDStr = m.contentID;
                cuisineNameStr = m.contentName;
            }else{
                cuisineIDStr = [NSString stringWithFormat:@"%@,%@",cuisineIDStr,m.contentID];
                cuisineNameStr = [NSString stringWithFormat:@"%@,%@",cuisineNameStr,m.contentName];
            }
        }
        
        self.authModel.cookingStyle = cuisineIDStr;
        self.authModel.cookingStyleName = cuisineNameStr;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self changeSubmitStateAction];
    };

}


/**
 展示热门商区选择的View
 */
- (void)showAreaSelectView
{
    if (self.authModel.areaName.length > 0) { //说明是被拒绝回来的.
        LZPopSelectCollectViewModel *m = [[LZPopSelectCollectViewModel alloc] init];
        m.contentID = self.authModel.areaId;
        m.contentName = self.authModel.areaName;
        m.isSelected = YES;
        self.selectedAreaArr = [NSArray arrayWithObject:m];
    }
    self.selectView.canSelectMore = NO;
    [self.selectView loadTitle:LZLocalizedString(@"res_auth_area", nil)];
    [self.selectView loadDataArr:[self.authPresenter getRestaurantAreaArrForPopSelectViewBaseSelectedAreaArr:self.selectedAreaArr]];
    [self.selectView showSelfAnimation];
    @weakify(self);
    self.selectView.selectedItemsBlock = ^(NSArray *resultArr){
        @strongify(self);
        self.selectedAreaArr = resultArr;
        LZPopSelectCollectViewModel *m = resultArr[0];
        self.authModel.areaName = m.contentName;
        self.authModel.areaId = m.contentID;
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        [self changeSubmitStateAction];
    };

}


/**
 当审核被拒绝,进入页面,请求到数据后.填充菜系, 热门商区等数据
 */
- (void)fillCookingStyleAndHotAreaWhenAuthRegetced
{
    //填充选择的菜系数据
    self.selectedCuisineArr = [self.authPresenter fillCookingStyleAndCallBackSelectedCookingStyleArrWhenAuthRegetcedWithAuthModel:self.authModel];
    
    //热门商区是单选 在showAreaSelectView 方法中已经处理
    
    //填充城市  根据城市编号获取城市名
    self.authModel.cityName = [CityManager returnTheCityNameWithCityCode:self.authModel.cityCode];
}

/**
 根据输入内容修改submit按钮状态
 */
- (void)changeSubmitStateAction
{
    self.submitBtn.userInteractionEnabled = NO;
    [self.submitBtn setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    
    if (self.authModel.restaurantName.length < 2) {
        return;
    }
    
    if (self.authModel.cookingStyle.length == 0) {
        return;
    }
    
    if (self.authModel.restaurantAddress.length < 2) {
        return;
    }
    
    if (self.authModel.mapLocationAddress.length < 2) {
        return;
    }
    
    if (self.authModel.areaName.length == 0) {
        return;
    }
    
    if (self.authModel.cellphone.length < 2) {
        return;
    }
    
    if (self.authModel.openTime.length < 2) {
        return;
    }
    
    if (self.authModel.closeTime.length < 2) {
        return;
    }
    
    if (self.authModel.companyName.length < 2) {
        return;
    }
    
    if (self.authModel.licencePhoto.length == 0) {
        return;
    }
    
    if ([self.authModel.paymentMethod isEqualToString:@"2"]){
        if (self.authModel.bankName.length == 0 || self.authModel.bankNumber.length == 0) {
            return;
        }
    }else if ([self.authModel.paymentMethod isEqualToString:@"1"]){
        if (self.authModel.paypalNumber.length == 0) {
            return;
        }
    }else{
        return;
    }
    
    self.submitBtn.userInteractionEnabled = YES;
    [self.submitBtn setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
    
}

#pragma mark -
#pragma mark cell delegate

/**
 填写cell返回相应的值
 
 @param text <#text description#>
 @param indexp <#indexp description#>
 */
- (void)returnTextViewContent:(NSString *)text withIndexPath:(NSIndexPath *)indexp
{
    if (indexp.section == 0) {
        switch (indexp.row) {
            case 0:
                self.authModel.restaurantName = text;
                [self reloadTableViewSection:0 row:0];
                break;
            case 2:
                self.authModel.restaurantAddress = text;
                [self reloadTableViewSection:0 row:2];
                break;
            case 6:
                self.authModel.cellphone = text;
                [self reloadTableViewSection:0 row:6];
                break;
            default:
                break;
        }
    }else if (indexp.section == 1){
        if (indexp.row == 0) {
            self.authModel.companyName = text;
            [self reloadTableViewSection:1 row:0];
        }
    }
    
    [self changeSubmitStateAction];
}

/**
 选择的cell.爆漏出相应cell
 
 @param indexPath <#indexPath description#>
 */
- (void)clickSelectCellWithIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            DLog(@"open  cuisine");
            if (self.authPresenter.restaurantCuisineArr.count != 0) {
                [self showCuisineSelectView];
            }else{
                [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
                [self.authPresenter getRestaurantCuisineSuccess:^(NSArray *cuisineArr) {
                    @strongify(self);
                    [self stopLoadingViewForView:self.view];
                    [self showCuisineSelectView];
                } Failure:^(NSString *fail) {
                    @strongify(self);
                    [self stopLoadingViewForView:self.view];
                }];
            }
            
        }else if (indexPath.row == 3){
            DLog(@"open map");
//            self.authModel.mapLocationAddress = @"aaaaaaaaaaa";
//            self.authModel.mapLocationLatitude = 23.33333;
//            self.authModel.mapLocationLongitude = 123.9999;
//            self.authModel.cityCode = @"BH000";
            
            LZMapViewController *mapVc = [[LZMapViewController alloc] init];
            mapVc.authModel = self.authModel;
            [self.navigationController pushViewController:mapVc animated:YES];
            @weakify(self);
            mapVc.chooseMapAddressBlock = ^(LZRestaurantAuthModel *authModel){
                @strongify(self);
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                [self changeSubmitStateAction];
            };
            
        }else if (indexPath.row == 4){//城市选择
            DLog(@"open city vc");
            LZSearchCityViewController *vc = [[LZSearchCityViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            @weakify(self);
            vc.selectCityBlock = ^(NSString *cityName,NSString *cityCode){
                @strongify(self);
                self.authModel.cityName = cityName;
                self.authModel.cityCode = cityCode;
                
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            };
            
        }else if (indexPath.row == 5){
            DLog(@"open area");
            if (self.authPresenter.restaurantAreaArr.count != 0) {
                [self showAreaSelectView];
            }else{
                [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
                [self.authPresenter getHotAreaSuccess:^(NSArray *areaArr) {
                    @strongify(self);
                    [self stopLoadingViewForView:self.view];
                    [self showAreaSelectView];
                    
                } Failure:^(NSString *fail) {
                    @strongify(self);
                    [self stopLoadingViewForView:self.view];
                }];
            }
        }
    }else if (indexPath.section == 1){
         if (indexPath.row == 2) {
            DLog(@"open account");
            LZPaymentAccountViewController *vc = [[LZPaymentAccountViewController alloc] init];
            vc.authModel = self.authModel;
            [self.navigationController pushViewController:vc animated:YES];
            vc.confirmAccountBlock = ^(LZRestaurantAuthModel *authModel){
                @strongify(self);
                [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
                [self changeSubmitStateAction];
            };
         }
   }
}


/**
 时间选择的cell,暴露出是开始,还是结束
 
 @param isBegin <#isBegin description#>
 */
- (void)clickTimeLabelAndIsBeginTime:(BOOL)isBegin
{
    @weakify(self);
    if (isBegin) {
        DLog(@"选择了开始时间");
        [self.selectTimeView showTimeView:self.authModel.openTime andTimeType:SELECT_TIME_TYPE_Start];
        
        self.selectTimeView.selectValueBlock = ^(NSString * value) {
            @strongify(self);
            self.authModel.openTime = value;
            [self.tableView reloadData];
            [self changeSubmitStateAction];
        };
        
    }else{
        DLog(@"选择结束时间");
        [self.selectTimeView showTimeView:self.authModel.closeTime andTimeType:SELECT_TIME_TYPE_End];

        self.selectTimeView.selectValueBlock = ^(NSString * value) {
            @strongify(self);
            self.authModel.closeTime = value;
            [self.tableView reloadData];
            [self changeSubmitStateAction];
        };
    }
}

/**
 上传 营业执照的cell 暴露点击事件
 */
- (void)clickLicenseImageViewAction
{
    DLog(@"choose  photo");
    [self.actionSheet ReloadTableViewArrayTitle:@[@[LZLocalizedString(@"change_takephoto", nil), LZLocalizedString(@"res_auth_phone_album", nil)], @[LZLocalizedString(@"cancel", nil)]]];
    [self.actionSheet ShowView];
}


#pragma mark -
#pragma mark table delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        UITableViewHeaderFooterView *v = [[UITableViewHeaderFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        v.contentView.backgroundColor = UIColorFromRGB(0xf0f0f0, 1);
        return v;
    }
    
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LZRestaurantAuthTableSectionHeadView *v = (LZRestaurantAuthTableSectionHeadView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:sectionHead];
    v.contentView.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        [v loadImg:@"restaurant_auth_res_info" Title:LZLocalizedString(@"res_auth_restaurant_info", nil)];
    }else if (section == 1){
        [v loadImg:@"restaurant_auth_company_info" Title:LZLocalizedString(@"res_auth_company_info", nil)];
    }
    
    return v;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 8;
    }
    
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WS(wSelf);
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {//餐厅名称
            return [LZRestaurantAuthTextCell getCellHeightWithText:self.authModel.restaurantName];
        }else if (indexPath.row == 2){//餐厅地址
            return [LZRestaurantAuthTextCell getCellHeightWithText:self.authModel.restaurantAddress];
        }else if (indexPath.row == 6){//电话
            return [LZRestaurantAuthTextCell getCellHeightWithText:self.authModel.cellphone];
        }else if (indexPath.row == 1 ){//菜系
            return [LZRestaurantAuthSelectCell getCellHeightWithContext:self.authModel.cookingStyleName cellNameText:LZLocalizedString(@"res_auth_cuisine", nil)];
        }else if (indexPath.row == 3){//地图定位
            return [LZRestaurantAuthSelectCell getCellHeightWithContext:self.authModel.mapLocationAddress cellNameText:LZLocalizedString(@"res_auth_map_location", nil)];
        }else if (indexPath.row == 5){//热门商区
            return [LZRestaurantAuthSelectCell getCellHeightWithContext:self.authModel.areaName cellNameText:LZLocalizedString(@"res_auth_area", nil)];
        }else if (indexPath.row == 7){//时间
           return [tableView fd_heightForCellWithIdentifier:openTimeCell cacheByKey:indexPath configuration:^(id cell) {
               [cell loadBeginTime:wSelf.authModel.openTime andEndTime:wSelf.authModel.closeTime];
           }];
        }else if (indexPath.row == 4){//城市选择
            return [LZRestaurantAuthSelectCell getCellHeightWithContext:self.authModel.cityName cellNameText:LZLocalizedString(@"res_auth_city_location", nil)];
        }
    }else{
        if (indexPath.row == 0) {
            return [LZRestaurantAuthTextCell getCellHeightWithText:self.authModel.companyName];
        }else if (indexPath.row == 1){
            return [tableView fd_heightForCellWithIdentifier:licenseCell cacheByKey:indexPath configuration:^(id cell) {
                [cell loadLicenseImgWithURL:@""];
            }];
        }else{//支付方式
            NSString *str = @"";
            if ([self.authModel.paymentMethod isEqualToString:@"1"]) {
                str = self.authModel.paypalNumber;
            }else if ([self.authModel.paymentMethod isEqualToString:@"2"]){
                str = [NSString stringWithFormat:@"%@ %@",self.authModel.bankName,self.authModel.bankNumber];
            }
            return [LZRestaurantAuthSelectCell getCellHeightForAccountCellWithContent:str];
        }
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0 || indexPath.row == 2 || indexPath.row == 6) {
            
            LZRestaurantAuthTextCell *cell = [tableView dequeueReusableCellWithIdentifier:textCell];
            cell.restaurantAuthTextCellDelegate = self;
            [cell loadTextCellWithIndexPath:indexPath andModel:self.authModel];
            [cell changeCellTextViewEnabled:!self.isWaitAuth];
            
            return cell;
            
        }else if (indexPath.row == 1 || indexPath.row == 3 || indexPath.row == 5){
            
            LZRestaurantAuthSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:selectCell];
            cell.restaurantAuthSelectCellDelegate = self;
            [cell loadSelectCellWithIndexPath:indexPath andModel:self.authModel];
            [cell changeCellEnabled:!self.isWaitAuth];
            
            return cell;
            
        }else if (indexPath.row == 7){
            LZRestaurantAuthOpenTimeSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:openTimeCell];
            cell.restaurantAuthOpenTimeCellDelegate = self;
            [cell loadBeginTime:self.authModel.openTime andEndTime:self.authModel.closeTime];
            [cell changeCellEnabled:!self.isWaitAuth];
            
            return cell;
        }else if (indexPath.row == 4){//城市选择
            LZRestaurantAuthSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:selectCell];
            cell.restaurantAuthSelectCellDelegate = self;
            [cell loadSelectCellWithIndexPath:indexPath andModel:self.authModel];
            [cell changeCellEnabled:!self.isWaitAuth];
            
            return cell;
        }
    }else{
        if (indexPath.row == 0) {
            LZRestaurantAuthTextCell *cell = [tableView dequeueReusableCellWithIdentifier:textCell];
            cell.restaurantAuthTextCellDelegate = self;
            [cell loadTextCellWithIndexPath:indexPath andModel:self.authModel];
            [cell changeCellTextViewEnabled:!self.isWaitAuth];
            
            return cell;
            
        }else if (indexPath.row == 1){
            
            LZRestaurantAuthLicenseCell *cell = [tableView dequeueReusableCellWithIdentifier:licenseCell];
            cell.restaurantAuthLicenseCellDelegate = self;
            [cell loadLicenseImgWithURL:self.authModel.licencePhoto];
            [cell changeCellEnable:!self.isWaitAuth];
            return cell;
            
        }else{
            LZRestaurantAuthSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:selectCell];
            cell.restaurantAuthSelectCellDelegate = self;
            [cell loadSelectCellWithIndexPath:indexPath andModel:self.authModel];
            [cell changeCellEnabled:!self.isWaitAuth];
            return cell;
        }
    }
    
    return nil;
}

#pragma mark -
#pragma mark 初始化
- (LZPopSelectView *)selectView
{
    if (_selectView) {
        return _selectView;
    }
    
    _selectView = [[NSBundle mainBundle] loadNibNamed:@"LZPopSelectView" owner:self options:nil].lastObject;
    _selectView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    return _selectView;
}

- (LZSelectDateView *)selectTimeView {
    if (_selectTimeView == nil) {
        _selectTimeView = [[LZSelectDateView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andSelectType:SELECT_TYPE_TIME];
    }
    return _selectTimeView;
}

- (LZActionSheet *)actionSheet {
    if (_actionSheet == nil) {
        LZActionSheet *sheet = [[LZActionSheet alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _actionSheet = sheet;
        [_actionSheet creatHeaderWithTitle:LZLocalizedString(@"res_auth_choose_img_sheet_title", nil) andHeight:51];
        [[UIApplication sharedApplication].keyWindow addSubview:_actionSheet];
        
        WS(weakSelf);
        _actionSheet.ClickSheetBlock = ^(NSIndexPath *indexPath, id obj) {
            if (indexPath.section == 0) {
                [weakSelf LASheetClickedButtonAtIndex:indexPath.row];
            }
        };
    }
    
    return _actionSheet;
}

- (LZImagePickerManager*)pictureManager {
    if (_pictureManager) {
        return _pictureManager;
    }
    LZImagePickerManager *manager = [[LZImagePickerManager alloc] init];
    manager.allowsEditing = NO;
    manager.delegate = self;
    _pictureManager = manager;
    return _pictureManager;
}


- (LZRestaurantAuthPresenter *)authPresenter
{
    if (_authPresenter) {
        return _authPresenter;
    }
    
    _authPresenter = [[LZRestaurantAuthPresenter alloc] init];
    return _authPresenter;
}

- (LZUploadImagePresenter *)uploadImagePresenter
{
    if (_uploadImagePresenter) {
        return _uploadImagePresenter;
    }
    _uploadImagePresenter = [[LZUploadImagePresenter alloc] init];
    return _uploadImagePresenter;
}


@end
